'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Minus, Plus, ArrowLeft, Wallet } from 'lucide-react';
import { useWeb3Modal } from '@web3modal/wagmi/react';
import { useAccount, useDisconnect, useSendTransaction, useWaitForTransactionReceipt, useSwitchChain } from 'wagmi';
import { parseEther } from 'viem';
import toast from 'react-hot-toast';

type TokenData = {
  name: string;
  totalAmount: string;
  each: string;
  mintRate: string;
  tokenMechanism: string[]; 
  raised: number;
  target: number;
  currency: string;
  oversubscriptionInfo: string;
  formula: string;
  // 'status' is no longer needed, it's controlled by the timer
};

const tokenData: TokenData = {
  name: 'C4PAD',
  totalAmount: '10000000000',
  each: '100 copies',
  mintRate: '1 OKB = 200,000 tokens',
  tokenMechanism: [
    '2% dividends',
    '2% lp',
    '2% donation',
  ],
  raised: 116.45, 
  target: 500,
  currency: 'OKB',
  oversubscriptionInfo: 'Core Rights and Utilities of the C4 Platform Token: 1. Revenue Sharing & Deflationary Mechanism - Fee Capture and Staking Dividends; 2. Exclusive Launchpad Access & Priority Rights - Guaranteed Allocation and Priority Purchase; 3. Platform Governance & Voting Power - Community Governance and Right to Propose; 4. Social & Live Streaming Ecosystem Privileges - Identity Status and Social Currency; 5. Enhanced Staking & Airdrop Capture - Yield Amplification and Ecosystem Airdrops.',
  formula: '$C4 serves as the governance token, empowering holders with voting rights, guaranteed whitelist spots, staking dividends from platform revenue, and exclusive access to high-quality project launches across all chains.',
};

// Define the countdown target date
const COUNTDOWN_TARGET_DATE = new Date('2025-10-24T00:00:00');

export function MintPage() {
  const router = useRouter();
  const [quantity, setQuantity] = useState(1);
  const [timeLeft, setTimeLeft] = useState({ days: 0, hours: 0, minutes: 0, seconds: 0 });
  const [isEnded, setIsEnded] = useState(false);
  
  // Web3 hooks
  const { open } = useWeb3Modal();
  const { address, isConnected, chain } = useAccount();
  const { disconnect } = useDisconnect();
  const { switchChain } = useSwitchChain();
  const { sendTransaction, data: hash, isPending } = useSendTransaction();
  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash,
  });

  // Target address for payments
  const TARGET_ADDRESS = '0x9b5fde30415c21a4675ade7ad6708c1a484c7e14';
  const XLAYER_CHAIN_ID = 196;

  useEffect(() => {
    // Set up a timer that updates every second
    const timer = setInterval(() => {
      const now = new Date();
      const difference = COUNTDOWN_TARGET_DATE.getTime() - now.getTime();

      if (difference > 0) {
        // Calculate remaining time
        const days = Math.floor(difference / (1000 * 60 * 60 * 24));
        const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
        const minutes = Math.floor((difference / 1000 / 60) % 60);
        const seconds = Math.floor((difference / 1000) % 60);
        setTimeLeft({ days, hours, minutes, seconds });
        setIsEnded(false);
      } else {
        // Countdown has finished
        setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 });
        setIsEnded(true);
        clearInterval(timer);
      }
    }, 1000);

    // Cleanup function to clear the interval when the component unmounts
    return () => clearInterval(timer);
  }, []);

  const progressPercentage = Math.round((tokenData.raised / tokenData.target) * 100);
  const visualProgress = Math.min(progressPercentage, 100);

  const handleQuantityChange = (amount: number) => {
    setQuantity((prev) => Math.max(1, prev + amount));
  };

  const handleQuantityInput = (value: string) => {
    const numValue = parseInt(value);
    if (!isNaN(numValue) && numValue > 0) {
      setQuantity(numValue);
    } else if (value === '') {
      setQuantity(1);
    }
  };

  const handleBuy = async () => {
    if (!isConnected) {
      open();
      return;
    }

    // Check if on correct network
    if (chain?.id !== XLAYER_CHAIN_ID) {
      toast.error('Please switch to OKX X Layer network');
      try {
        await switchChain({ chainId: XLAYER_CHAIN_ID });
      } catch (error) {
        console.error('Failed to switch network:', error);
        toast.error('Failed to switch to OKX X Layer network. Please switch manually in your wallet.');
        return;
      }
    }

    try {
      const amount = (0.01 * quantity).toString(); // 0.01 OKB per quantity
      toast.success(`Sending ${amount} OKB...`);
      sendTransaction({
        to: TARGET_ADDRESS as `0x${string}`,
        value: parseEther(amount),
      });
    } catch (error) {
      console.error('Transaction failed:', error);
      toast.error('Transaction failed. Please try again.');
    }
  };

  const formatAddress = (addr: string) => {
    return `${addr.slice(0, 6)}...${addr.slice(-4)}`;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-950 via-purple-900 to-pink-900 text-slate-100 flex items-center justify-center p-4 sm:p-6 font-sans relative overflow-hidden">
      {/* Animated background elements */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-purple-500 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob" />
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-yellow-500 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-2000" />
        <div className="absolute -bottom-40 left-20 w-80 h-80 bg-pink-500 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-4000" />
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-blue-500 rounded-full mix-blend-multiply filter blur-3xl opacity-10 animate-pulse" />
      </div>
      
      <div className="w-full max-w-4xl bg-white/5 backdrop-blur-xl rounded-3xl border border-white/10 p-8 md:p-12 space-y-10 z-10 shadow-2xl">

        {/* Back to Home Button and Wallet Connection */}
        <div className="flex justify-between items-center -mt-2">
          <button 
            onClick={() => router.push('/')}
            className="group flex items-center gap-2 px-5 py-2.5 bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white rounded-full transition-all duration-300 backdrop-blur-sm border border-white/20 hover:border-white/30"
          >
            <ArrowLeft size={18} className="transition-transform group-hover:-translate-x-1" />
            <span className="text-sm font-medium">Back Home</span>
          </button>

          {/* Wallet Connection Button */}
          <div>
            {isConnected ? (
              <div className="flex items-center gap-3">
                {chain?.id !== XLAYER_CHAIN_ID && (
                  <button
                    onClick={() => switchChain({ chainId: XLAYER_CHAIN_ID })}
                    className="px-4 py-2.5 bg-orange-500/20 hover:bg-orange-500/30 border border-orange-500/50 hover:border-orange-500 text-orange-400 hover:text-orange-300 rounded-full transition-all duration-300 backdrop-blur-sm text-sm font-medium"
                  >
                    Switch to X Layer
                  </button>
                )}
                <div className="px-4 py-2.5 bg-green-500/20 border border-green-500/50 rounded-full backdrop-blur-sm">
                  <span className="text-sm font-medium text-green-400">
                    {address && formatAddress(address)}
                  </span>
                </div>
                <button
                  onClick={() => disconnect()}
                  className="px-5 py-2.5 bg-red-500/20 hover:bg-red-500/30 border border-red-500/50 hover:border-red-500 text-red-400 hover:text-red-300 rounded-full transition-all duration-300 backdrop-blur-sm text-sm font-medium"
                >
                  Disconnect
                </button>
              </div>
            ) : (
              <button
                onClick={() => open()}
                className="group flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-purple-500/20 to-pink-500/20 hover:from-purple-500/30 hover:to-pink-500/30 border border-purple-500/50 hover:border-purple-400 text-purple-300 hover:text-purple-200 rounded-full transition-all duration-300 backdrop-blur-sm"
              >
                <Wallet size={18} />
                <span className="text-sm font-medium">Connect Wallet</span>
              </button>
            )}
          </div>
        </div>

        {/* Header */}
        <div className="text-center space-y-4">
          <div className="inline-block">
            <h1 className="text-6xl md:text-7xl font-black bg-gradient-to-r from-yellow-400 via-pink-400 to-purple-400 bg-clip-text text-transparent tracking-tight">
              BUY
            </h1>
            <div className="h-1.5 bg-gradient-to-r from-yellow-400 via-pink-400 to-purple-400 rounded-full mt-2" />
          </div>
        </div>


        {/* --- COUNTDOWN TIMER (NEW) --- */}
        <div className="text-center">
            {isEnded ? (
                <div className="inline-block px-8 py-4 bg-red-500/20 border border-red-500/50 rounded-2xl backdrop-blur-sm">
                  <div className="text-2xl font-bold text-red-400 tracking-wide">Activity Ended</div>
                </div>
            ) : (
                <div className="flex items-center justify-center gap-3 md:gap-6">
                    <div className="text-center group">
                      <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4 md:p-6 border border-white/20 transition-all duration-300 hover:bg-white/15 hover:scale-105">
                        <div className="text-3xl md:text-5xl font-bold bg-gradient-to-br from-yellow-400 to-orange-400 bg-clip-text text-transparent">
                          {String(timeLeft.days).padStart(2, '0')}
                        </div>
                      </div>
                      <div className="text-xs md:text-sm text-slate-400 mt-2 font-medium">天</div>
                    </div>
                    <div className="text-3xl md:text-4xl text-white/30 font-light">:</div>
                    <div className="text-center group">
                      <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4 md:p-6 border border-white/20 transition-all duration-300 hover:bg-white/15 hover:scale-105">
                        <div className="text-3xl md:text-5xl font-bold bg-gradient-to-br from-pink-400 to-purple-400 bg-clip-text text-transparent">
                          {String(timeLeft.hours).padStart(2, '0')}
                        </div>
                      </div>
                      <div className="text-xs md:text-sm text-slate-400 mt-2 font-medium">时</div>
                    </div>
                    <div className="text-3xl md:text-4xl text-white/30 font-light">:</div>
                    <div className="text-center group">
                      <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4 md:p-6 border border-white/20 transition-all duration-300 hover:bg-white/15 hover:scale-105">
                        <div className="text-3xl md:text-5xl font-bold bg-gradient-to-br from-blue-400 to-cyan-400 bg-clip-text text-transparent">
                          {String(timeLeft.minutes).padStart(2, '0')}
                        </div>
                      </div>
                      <div className="text-xs md:text-sm text-slate-400 mt-2 font-medium">分</div>
                    </div>
                    <div className="text-3xl md:text-4xl text-white/30 font-light">:</div>
                    <div className="text-center group">
                      <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-4 md:p-6 border border-white/20 transition-all duration-300 hover:bg-white/15 hover:scale-105">
                        <div className="text-3xl md:text-5xl font-bold bg-gradient-to-br from-green-400 to-emerald-400 bg-clip-text text-transparent">
                          {String(timeLeft.seconds).padStart(2, '0')}
                        </div>
                      </div>
                      <div className="text-xs md:text-sm text-slate-400 mt-2 font-medium">秒</div>
                    </div>
                </div>
            )}
        </div>


        {/* Token Info Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-base md:text-lg">
          <div className="flex justify-between items-center p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-all duration-300">
            <span className="text-slate-400 font-medium">Name</span>
            <span className="font-semibold text-white">{tokenData.name}</span>
          </div>
          <div className="flex justify-between items-center p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-all duration-300">
            <span className="text-slate-400 font-medium">Total Amount</span>
            <span className="font-semibold text-white">{tokenData.totalAmount}</span>
          </div>
          <div className="flex justify-between items-center p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-all duration-300 md:col-span-2">
            <span className="text-slate-400 font-medium">Each</span>
            <span className="font-semibold text-white">{tokenData.each}</span>
          </div>
        </div>
        
        {/* Token Mechanism */}
        <div className="text-base md:text-lg bg-gradient-to-br from-purple-500/10 to-pink-500/10 rounded-2xl p-6 border border-white/10">
          <h3 className="text-slate-300 mb-4 font-semibold text-lg">Token Mechanism</h3>
          <div className="space-y-3">
            {tokenData.tokenMechanism.map((line, index) => (
              <div key={index} className="flex items-center gap-3 group">
                <div className="w-2 h-2 rounded-full bg-gradient-to-r from-yellow-400 to-pink-400 group-hover:scale-125 transition-transform" />
                <p className="text-slate-200 group-hover:text-white transition-colors">{line}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="w-full h-px bg-gradient-to-r from-transparent via-white/20 to-transparent" />

        {/* Progress Section */}
        <div className="space-y-4">
          <div className="flex justify-between items-center text-base md:text-lg">
            <span className="font-bold text-transparent bg-gradient-to-r from-green-400 to-emerald-400 bg-clip-text">
              Progress: {progressPercentage}%
            </span>
            <span className="text-slate-400 font-medium">
              {tokenData.raised} {tokenData.currency} / {tokenData.target} {tokenData.currency}
            </span>
          </div>
          <div className="relative w-full bg-white/10 h-10 rounded-full overflow-hidden backdrop-blur-sm border border-white/20">
            <div 
              className="absolute inset-0 bg-gradient-to-r from-green-400 via-emerald-400 to-cyan-400 transition-all duration-1000 ease-out rounded-full" 
              style={{ width: `${visualProgress}%` }}
            />
            <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-shimmer" />
          </div>
        </div>

        {/* Info Box */}
        <div className="bg-gradient-to-br from-blue-500/10 to-purple-500/10 rounded-2xl overflow-hidden border border-white/10 backdrop-blur-sm">
            <div className="p-6 text-slate-300 text-sm md:text-base leading-relaxed">
              {tokenData.oversubscriptionInfo}
            </div>
            <div className="bg-black/20 p-6 border-t border-white/10">
              <p className="text-transparent bg-gradient-to-r from-yellow-400 to-orange-400 bg-clip-text font-medium text-sm md:text-base leading-relaxed">
                {tokenData.formula}
              </p>
            </div>
        </div>

        {/* --- BUY CONTROLS (LAYOUT UPDATED) --- */}
        <div className="flex flex-col sm:flex-row items-stretch gap-4 pt-4">
          <div className="w-full sm:w-2/3 flex items-center justify-between bg-white/5 backdrop-blur-sm rounded-2xl border-2 border-yellow-400/50 p-2 hover:border-yellow-400 transition-all">
            <button 
              onClick={() => handleQuantityChange(-1)} 
              disabled={isEnded} 
              className="p-3 text-yellow-400 hover:bg-white/10 rounded-xl transition-all disabled:text-gray-600 disabled:cursor-not-allowed disabled:hover:bg-transparent"
            >
              <Minus size={24} />
            </button>
            <div className="text-center flex-1 px-4">
              <input
                type="number"
                min="1"
                value={quantity}
                onChange={(e) => handleQuantityInput(e.target.value)}
                disabled={isEnded}
                className="w-full text-center text-3xl md:text-4xl font-bold bg-transparent bg-gradient-to-r from-yellow-400 to-orange-400 bg-clip-text text-transparent outline-none [-moz-appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none disabled:cursor-not-allowed"
                style={{
                  WebkitTextFillColor: 'transparent',
                  backgroundClip: 'text',
                }}
              />
              <div className="text-xs text-slate-400 mt-1 space-y-0.5">
                <div>{(0.01 * quantity).toFixed(2)} OKB</div>
                <div className="text-emerald-400 font-medium">
                  ≈ {(quantity * 2000).toLocaleString()} C4PAD
                </div>
              </div>
            </div>
            <button 
              onClick={() => handleQuantityChange(1)} 
              disabled={isEnded} 
              className="p-3 text-yellow-400 hover:bg-white/10 rounded-xl transition-all disabled:text-gray-600 disabled:cursor-not-allowed disabled:hover:bg-transparent"
            >
              <Plus size={24} />
            </button>
          </div>
          <button 
            onClick={handleBuy}
            disabled={isEnded || isPending || isConfirming} 
            className="group relative w-full sm:w-1/3 bg-gradient-to-r from-yellow-400 via-orange-400 to-pink-400 text-white font-bold text-xl md:text-2xl py-5 rounded-2xl overflow-hidden transition-all duration-300 disabled:from-gray-700 disabled:to-gray-700 disabled:text-gray-500 disabled:cursor-not-allowed hover:shadow-2xl hover:shadow-yellow-400/50 hover:scale-105"
          >
            <span className="relative z-10 tracking-wider">
              {!isConnected ? 'CONNECT WALLET' : isPending || isConfirming ? 'PROCESSING...' : 'BUY'}
            </span>
            <div className="absolute inset-0 bg-gradient-to-r from-pink-400 via-purple-400 to-indigo-400 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          </button>
        </div>

        {/* Network Warning */}
        {isConnected && chain?.id !== XLAYER_CHAIN_ID && (
          <div className="p-4 bg-orange-500/20 border border-orange-500/50 rounded-xl backdrop-blur-sm">
            <p className="text-orange-400 text-sm font-medium">
              ⚠️ Please switch to OKX X Layer network to use OKB
            </p>
            <p className="text-slate-400 text-xs mt-1">
              Current network: {chain?.name || 'Unknown'}
            </p>
          </div>
        )}

        {/* Transaction Status */}
        {hash && (
          <div className="mt-4 p-4 bg-blue-500/20 border border-blue-500/50 rounded-xl backdrop-blur-sm">
            <p className="text-blue-400 text-sm">
              {isConfirming && 'Waiting for confirmation...'}
              {isConfirmed && '✅ Transaction confirmed!'}
            </p>
            {isConfirmed && (
              <p className="text-slate-400 text-xs mt-2">
                Transaction Hash: {hash.slice(0, 10)}...{hash.slice(-8)}
              </p>
            )}
          </div>
        )}
        
      </div>
    </div>
  );
}